<?php
/*
 * 文件缓存
 * @author     Mark <zhaody901@126.com>
 * @copyright  Copyright (c) 2013 lemon team
 * @version    $Id: 637f9691f2c2becc62da0e2773dddd8fd003a2e4 $
 * @time       14-2-7 上午10:25
 */
defined('IN_IXDCW') or exit('Access Denied');

/**
 * 缓存类, 所有的缓存均以文件缓存为主
 */
class dcache {

	public $pre;

	/**
	 * @var int 缓存的时间
	 */
	public $time;

	function __construct() {
		global $DT_TIME;
		$this->time = $DT_TIME;
	}

	function get($key) {
		Utils::isMd5($key) or $key = md5($this->pre.$key);
		$php = DT_CACHE.'/php/'.substr($key, 0, 2).'/'.$key.'.php';
		if(is_file($php)) {
			$str = File::get($php);
			$ttl = substr($str, 13, 10);
			if($ttl < $this->time) return '';
			return substr($str, 23, 1) == '@' ? substr($str, 24) : unserialize(substr($str, 23));
		} else {
			return '';
		}
	}

	function set($key, $val, $ttl = 600) {
		global $db, $CFG;
		Utils::isMd5($key) or $key = md5($this->pre.$key);
		$ttl = $this->time + $ttl;
		$sql = "REPLACE INTO {$db->getPre()}cache (`cacheid`,`totime`) VALUES ('$key','$ttl')";
		strpos($CFG['database'], 'mysqli') !== false ? mysqli_query($db->connid, $sql) : mysql_query($sql, $db->connid);
		$val = '<?php exit;?>'.$ttl.(is_array($val) ? serialize($val) : '@'.$val);
		return File::put(DT_CACHE.'/php/'.substr($key, 0, 2).'/'.$key.'.php', $val);
	}

	/**
	 * @param $key
	 * @return bool 删除缓存文件
	 */
	function rm($key) {
		Utils::isMd5($key) or $key = md5($this->pre.$key);
		return File::del(DT_CACHE.'/php/'.substr($key, 0, 2).'/'.$key.'.php');
	}

	function clear() {
		//File::dirDelete(DT_CACHE.'/php/');
	}

	function expire() {
		global $db;
		$result = $db->query("SELECT cacheid FROM {$db->getPre()}cache WHERE totime<$this->time LIMIT 100");
		while($r = $db->fetchArray($result)) {
			$cid = $r['cacheid'];
			$this->rm($cid);
			$db->query("DELETE FROM {$db->getPre()}cache WHERE cacheid='$cid'");
		}
	}
}